//
//  Enemy.m
//  CompGraf2
//
//  Created by Juan Niosi on 27/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Enemy.h"
#import "World.h"

@implementation Enemy

- (id)init:(MD2Model *)md2 withWalkSpeed:(GLfloat)walk withTurnSpeed:(GLfloat)turn startsAt:(MapNode *)origin views:(float)range
{
    self = [super init:md2 withWalkSpeed:walk withTurnSpeed:turn :origin];
    if (self) {
        startingPos = origin;
        viewRange = range;
        
        enemyState = ENEMY_GUARDING;
        
        self.position = [startingPos.worldPos getValues];
        world = [World getWorld];
        charCurrObj = NULL;
    }
    
    return self;
}

- (void)update:(float)deltaTime
{
    [super update:deltaTime];
    switch(enemyState)
    {
        case ENEMY_GUARDING:
            [self updateGuarding:deltaTime];
            break;
        case ENEMY_CHASING:
            [self updateChasing:deltaTime];
            break;
        default:
            break;
    }
}

- (void)updateGuarding:(float)deltaTime
{
    float srqDist = [world.mainCharacter getSqrDistance:self.position];
    if (srqDist < viewRange*viewRange)
    {
        [self setEnemyState:ENEMY_CHASING];
    }
}

- (void)pathToCharacter
{
    MapNode *curObj = [world.mainCharacter getCurrentObjective];
    if ([curObj equals:charCurrObj])
        return;
    
    charCurrObj = curObj;
    NSMutableArray *path = [[NSMutableArray alloc] initWithArray:[world.terrain getPath:currentPos :curObj]]; 

    [path removeLastObject];
    if ([path count] > 0)
        [self setPath:path];
}

- (void)updateChasing:(float)deltaTime
{
    float sqrDist = [world.mainCharacter getSqrDistance:self.position];
    if (sqrDist > 2)
    {
        [self pathToCharacter];
    }
}

- (void)setEnemyState:(ENEMY_STATE)newState
{
    enemyState = newState;
    switch (newState) {
        case ENEMY_GUARDING:
            break;
        case ENEMY_CHASING:
            
            break;
        default:
            break;
    }
}

- (void)dealloc
{
    [startingPos release];
    [super release];
}
@end
